// TaskTaskStorage.cpp

#include "TaskStorage.h"
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include "Task.h"

TaskStorage::TaskStorage(std::string inputFileName) {
	_fileName = inputFileName;
}

TaskStorage::~TaskStorage() {
	delete _taskPtr;
}

bool TaskStorage::isEmptyFile() {
	
	bool fileIsEmpty;
	
	_fileInput.open(_fileName.c_str(), std::fstream::app);
	_fileInput.peek();
	if(_fileInput.eof()) {
		fileIsEmpty = true;
	} else {
		fileIsEmpty = false;
	}
	_fileInput.close();

	return fileIsEmpty;
}

bool TaskStorage::loadFile(std::vector<Task> &taskList) {
	_fileInput.open(_fileName.c_str(), std::fstream::app);

	if(isEmptyFile()) {
		return false;
	} else { 
		while(_fileInput.is_open() && !_fileInput.eof()) {
		std::string nextLine;
		std::getline(_fileInput, nextLine);
		std::istringstream input(nextLine);
		//_taskPtr = new Task;
		//_taskPtr->convertStringToTask(input);
		Task newTask;
		newTask.convertStringToTask(input);
		_taskList.push_back(newTask);
		/*if(newTask.getCompleteStatus()) {
			_completedTask.push_back(newTask);
		} else {
			_notCompletedTask.push_back(newTask);
		}
		 delete _taskPtr;*/
	}
	}
	_fileInput.close();
	taskList = returnTaskList();
	return true;
}


bool TaskStorage::writeFile(std::vector<Task> contents) {
	//WriteNotCompletedTask();
	//WriteCompletedTask();
	updateTaskList(contents);
	writeTaskList();
	return true;
}

void TaskStorage::writeTaskList() {
	_fileOutput.open(_fileName.c_str(), std::fstream::trunc);
	for(unsigned int i = 1; i <= _taskList.size(); i++) {
		_fileOutput << _taskList[i-1].convertToString();
	}
	_fileOutput.close();
}

std::vector<Task> TaskStorage::returnTaskList() {
	return _taskList;
}

void TaskStorage::updateTaskList(std::vector<Task> updatedTaskList) {
	_taskList = updatedTaskList;
}

/*
void TaskStorage::WriteNotCompletedTask() {
	_fileOutput.open(_fileName.c_str(), std::fstream::trunc);
	for(unsigned int i = 1; i <= _notCompletedTask.size(); i++) {
		_fileOutput << _notCompletedTask[i-1].convertToString();
	}
	_fileOutput.close();
}
*/
/*
void TaskStorage::WriteCompletedTask() {
	_fileOutput.open(_fileName.c_str(), std::fstream::app);
	for(unsigned int i = 1; i <= _completedTask.size(); i++) {
		_fileOutput << _completedTask[i-1].convertToString();
	}
	_fileOutput.close();
}
*/
/*
std::vector<Task> TaskStorage::returnCompletedTask() {
	return _completedTask;
}
*/
/*
std::vector<Task> TaskStorage::returnNotCompletedTask() {
	return _notCompletedTask;
}
*/
/*
void TaskStorage::updateCompletedTask(std::vector<Task> completedTask) {
	_completedTask = completedTask;
}
*/
/*
void TaskStorage::updateNotCompletedTask(std::vector<Task> notCompletedTask) {
	_notCompletedTask = notCompletedTask;
}
*/